<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once("Core.php");
class CI_Order extends CI_Core{
	private $table = 'order';
	function __construct(){
		parent::__construct();
		$this->database('default');
		$this->ci->load->library('Huashang/shopcart');
	}
	//获取订单列表
	public function getlist($tj=array(),$tj2=array(),$web='admin',$pagesize=12,$page=1){
		$this->open('order');
		$data=$web=='admin'? $this->get_list($tj,$tj2):$this->front_get_list($tj,$tj2,$pagesize,$page);
		foreach($data['result'] as $k=>$v){
			$data['result'][$k]['detail']=$this->get_all('order_id,goods_id,goods_title,goods_amount,goods_price',array('order_id'=>$v['id']),'order_detail');
		}
		ob_clean();
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
	    return $this->status(true, $rs);
	}
	//统计订单
	public function countPrice($tj=array(),$tj2=array(),$sum='count(*)'){
		$this->open('order');
		$rs=$this->count_total($tj,$tj2,$sum);
		return $this->status(true, $rs);
	}
	//挑皮网生成订单
	public function createOrder($row){
		//发送短信
		$this->ci->load->library('Huashang/sms');
		$rs=$this->getShopCart($row['user_id']);
		
		foreach($rs as $v){
			
			$order_sn = sprintf("%u",crc32(uniqid()));
			$bigOrder=array(
				'shop_id'      =>$v['id'],
				'order_sn'     =>$order_sn,
				'total_price'  =>$v['total'],
				'freight'      =>0,
				'amount'       =>0,
				'pay_ment'     =>1,
				'payee'        => $row['payee'],
				'address'      => $row['address'],
				'phone'        => $row['phone'],
				'user_id'      => $row['user_id'],
				'user_name'    => $row['user_name'],
				'add_time'     => time(),
				'pay_wechat'   => $row['pay_wechat'],
			);
			$this->db->insert('order',$bigOrder);
			$id = $this->db->insert_id();
			//批量插入订单商品
			$item = array();
			#echo '<pre>';print_r($v['big']);exit;
			foreach($v['big'] as $t){
				$item=array(
					'order_id'     => $id,
					'goods_id'     => $t['goods_id'],
					'goods_amount' => $t['goods_amount'],
					//'rzg_amount'   => $t['rzg_amount'],
					'goods_title'  => $t['title'],
					'user_id'      => $row['user_id'],
					'user_name'    => $row['user_name'],
					'goods_pic'    =>$t['goods_pic'],
					'goods_add_time'=>time(),
					#'goods_total' => $t[']
				);
				$this->db->insert('order_detail',$item);
				$bid = $this->db->insert_id();
				$small=array();
				foreach($t['goods'] as $ttt){
					$small[]=array(
						'o_id'=>$bid,
						'goods_id'=>$ttt['id'],
						'goods_title'=>$ttt['title'],
						'goods_amount'=>$ttt['s_amount'],
						'goods_price'=>$ttt['total'],
						
						'rzg_amount'=>$ttt['rzg_amount'],
						'rzg_price'=>$ttt['rzg_total'],
						'dan_price'=>$ttt['price'],
					);
				}
				$this->db->insert_batch('order_info',$small); 
			}
			//$this->db->insert_batch('order_detail',$item); 
			
			$u=$this->get_one('phone',array('id'=>$v['id']),'user');
			if($u['phone']){
				$this->ci->sms->OrderMsg($u['phone'],'皮革订单号为'.$order_sn);
				
			}
			//$this->ci->sms->sendSms('');
			
		}
		
		$cart_ids = $this ->ci ->shopcart -> getShopCartChange($row['user_id']); //获取购物车被选中的购物车 id
		if(empty($cart_ids) && is_array($cart_ids)){
			foreach($cart_ids as $key => $cart_id){
				$this->db->delete('cart_info',array('user_id'=>$row['user_id'],'cart_id' => $cart_id));
			}
		}
		//删除购物车
		$this->db->delete('shopcart',array('user_id'=>$row['user_id'],'status'=>1));
		$this->db->delete('cart_info',array('user_id'=>$row['user_id'],'status'=>1));
		return $this->status(true, array('sn'=>$order_sn,'total'=>$total,'freight'=>$row['freight']));
	}
	//读取购物车信息
	public function getShopCart($uid){
		$shop=$this->get_all('*',array('user_id'=>$uid?$uid:'-1','status' =>1),'shopcart',array('group'=>'shop_id'));
		foreach($shop as $v){
			$data['total']=0;
			$tj2=array('join'=>'goods','on'=>'b.goods_id=a.id','a_fields'=>'a.id,a.title,a.price,a.pictures,a.en_title,a.rzg_price');
			$rs[$v['shop_id']]['big']=array_pop($this->ci->shopcart->pub_search(array('b.shop_id'=>$v['shop_id'],'user_id'=>$uid,'b.status' => 1),$tj2));
			foreach($rs[$v['shop_id']]['big'] as $k=>$t){
				$rs[$v['shop_id']]['big'][$k]['goods_pic']=array_shift(json_decode($t['pictures'],true));
				$price=0;
				$tj2=array('join'=>'goods','on'=>'b.s_id=a.id','a_fields'=>'a.id,a.title,a.stocks,a.pictures,a.en_title,a.price');
				$rs[$v['shop_id']]['big'][$k]['goods']=$this->get_all('*',array('cart_id'=>$t['cid'],'user_id'=>$uid,'status' => 1),'cart_info',$tj2);
				
				foreach($rs[$v['shop_id']]['big'][$k]['goods'] as $kk=>$tt){
					$rs[$v['shop_id']]['big'][$k]['goods'][$kk]['total']=$tt['s_amount']*$t['price'];
					$rs[$v['shop_id']]['big'][$k]['goods'][$kk]['rzg_total']=$tt['rzg_amount']*$t['rzg_price'];
					$data['total']+=$tt['s_amount']*$t['price'];
					$data['total']+=$tt['rzg_amount']*$t['rzg_price'];
					$data['num']+=$tt['s_amount'];
					$price+=$data['total'];
				}
				if(empty($rs[$v['shop_id']]['big'][$k]['goods'])){
					unset($rs[$v['shop_id']]['big'][$k]);
				}
			}
			$rs[$v['shop_id']]['total']=$data['total'];
			$rs[$v['shop_id']]['id']=$v['shop_id'];
			if(empty($rs[$v['shop_id']]['big'])){
				unset($rs[$v['shop_id']]);
			}
		}
		#echo '<pre>';print_R($rs);exit;
		//print_r($rs);exit;
		return $rs;
	}

	//扣除积分
	public function updateUserScores($uname,$scores,$source_id){
		 $this->ci->load->library('Huashang/user');
		 $rs=array_shift($this->ci->user->addScoreRecord($uname,"-$scores",'积分兑换商品',3,$source_id));
		 return $rs;
	}
	
	//修改订单支付状态
	public function updatePayStatus($sn){
		$this->db->update('order',array('order_status'=>2,'pay_time'=>time()),array('order_sn'=>$sn));
		$arr = $this->get_one('id',array('order_sn'=>$sn),'order');
		$this->db->update('order_detail',array('goods_status'=>2),array('order_id'=>$arr['id']));
		//if($arr['order_type']==2) $this->db->update('order',array('ship_status'=>3),array('id'=>$arr['id']));
		return $this->status(true);
	}
	//修改订单支付方式
	public function updatePayMent($sn,$pay){
		if(!$sn) return $this->status(false, 'order_sn is null');
		$this->db->update('order',array('pay_ment'=>$pay),array('order_sn'=>$sn));
		return $this->status(true, 'OK');
	}
	
	//修改订单微信支付
	public function updateWechatPay($sn,$pay_wechat){
		if(!$sn) return $this->status(false, 'order_sn is null');
		$this->db->update('order',array('pay_wechat'=>$pay_wechat),array('order_sn'=>$sn));
		return $this->status(true, 'OK');
	}
	//取消订单
	public function cancelOrder($sn,$staff='1'){
		$rs = $this->get_one('*',array('order_sn'=>$sn),'order');
		if($rs==array()){
			return $this->status(false);
		}else{
			if($rs['ship_status']==1 || $rs['order_status']==2) return $this->status(false);
			$this->db->update('order',array('order_status'=>4),array('order_sn'=>$sn));
			$this->db->update('order_detail',array('goods_status'=>4),array('order_id'=>$rs['id']));
			
			$this->db->insert('order_log',array('order_sn'=>$sn,'type'=>'1', 'memo'=>'取消订单','staff'=>$staff,'add_time'=>time()));
			return $this->status(true);
		}
	}
	//删除订单(软删除)
	public function delOrder($sn){
		$rs=$this->order_info($sn,false);
		if($rs==array()){
			return $this->status(false);
		}else{
			if($rs['is_del']==2) return $this->status(false);
			$this->db->update('order',array('is_del'=>2,'order_status' => 4),array('order_sn'=>$sn));
			return $this->status(true);
		}
	}
	//删除订单(无记录)
	public function remove(){
		$ids = explode(',', $this->ci->input->post('id'));
		$this->db->where_in('id', $ids);
		$this->db->delete('order');
		$this->db->where_in('order_id', $ids);
		$this->db->delete('order_detail');
	}
	//修改订单
	public function save($rs,$staff='1'){
		$arr=array(
				'order_status'=>2,
				'pay_time'=>time(),
				'express_ment'=>$rs['express_ment'],
				'express_number'=>$rs['express_number'],
				'express_time'=>strtotime($rs['express_time']),
		);
		if($rs['express_number']) $arr['ship_status']=1; 
		if($rs['order_status']==2){
			$this->db->update('order',$arr,array('id'=>$rs['id']));
			$this->db->update('order_detail',array('goods_status'=>2),array('order_id'=>$rs['id']));
			$this->db->insert('order_log',array('order_sn'=>$rs['order_sn'],'type'=>'2', 'memo'=>'修改已付款','staff'=>$staff,'add_time'=>time()));
			echo '{"status":"OK","msg":"执行成功"}';
		}else if($rs['order_status']==4){
			$a=array_shift($this->cancelOrder($rs['order_sn'],$staff));
			if($a) echo '{"status":"OK","msg":"执行成功"}'; else echo '{"status":"ERROR","msg":"执行失败"}';
		}else{
			echo '{"status":"OK","msg":"执行成功"}';
		}
	}
	//修改已收货
	public function editShip($id){
		$this->db->update('order',array('ship_status'=>3,'ship_time'=>time()),array('id'=>$id));
		echo '{"status":"OK","msg":"执行成功"}';
	}

	//支付订单
	public function pay($method,$id,$total,$source='WAP'){
		if($source=='WAP'||$source=='APP'||$source=='MOBILE'){//来源：微信，APP，手机站
			if($method==1){//支付宝
				$this->ci->load->library('Huashang/alipaynew');
				$this->ci->alipaynew->pay(array(
					'total'       => $total,
					'order_sn'    => $id,
					'subject'     => "支付订单: $id",
					'notify_url'  => WEB.'api/alipayBack',
					'back_url'    => WEB.'api/alipayFront',
					'merchant_url'=> WEB.'customer/myorder',
				));
			}else if($method==2){//银联支付
				$this->ci->load->library('Huashang/unionpay');
				$this->ci->unionpay->unionpayWap(array(
					'sn'       => $id,
					'total'    => $total,
					'frontUrl' => WEB.'api/unionFront',
					'backUrl'  => WEB.'api/unionBack',
				));
			}
		}else{
			
		}
	}
	
	
	//检查库存有效性 array(array(gid=>1,amount=>1),...)
	public function stocksAvailable($group){
		foreach($group as $k=>$v){
			$rs = $this->get_one('stocks',array('id'=>$v['gid']),'goods');
			$group[$k]['status']=$v['amount']<=$rs['stocks']?true:false;
		}
		return $this->status(true,$group);
	}
	
	//自由查询
	public function pub_search($tj=array(),$tj2=array()){
		$arr = $this->get_all('*',$tj,'order',$tj2);
		return $this->status(true, $arr);
	}
	//自由查询明细
	public function pub_search_detail($tj=array(),$tj2=array()){
		$arr = $this->get_all('*',$tj,'order_detail',$tj2);
		return $this->status(true, $arr);
	}
	//查看一条订单
	public function order_info($sn,$detail=true){
		$rs = $this->get_one('*',array('order_sn'=>$sn),'order');
		if($rs!=array()) $rs['add_time']=date('Y-m-d H:i',$rs['add_time']);
		if($detail){
			if($rs!=array()){
				$arr = $this->get_all('*',array('order_id'=>$rs['id']),'order_detail',array('join'=>'goods','on'=>'b.goods_id=a.id','a_fields'=>'a.pictures,a.stocks,a.weight'));
				foreach($arr as $k=>$v){
					$arr[$k]['goods_list']=$this->get_all('*',array('o_id'=>$v['id']),'order_info');
				}
				$rs['detail']=$arr;
			}
		}
		return $this->status(true, $rs);
	}
	//按ID查询订单
	public function getByOrderId($id,$detail=true){
		$rs = $this->get_one('*',array('id'=>$id),'order');
		if($rs!=array()) $rs['add_time']=date('Y-m-d H:i',$rs['add_time']);
		if($detail){
			if($rs!=array()){
				$arr = $this->get_all('*',array('order_id'=>$rs['id']),'order_detail',array('join'=>'goods','on'=>'b.goods_id=a.id','a_fields'=>'a.pictures,a.stocks,a.weight'));
				foreach($arr as $k=>$v){
					$arr[$k]['goods_list']=$this->get_all('*',array('o_id'=>$v['id']),'order_info');
				}
				$rs['detail']=$arr;
			}
		}
		return $this->status(true, $rs);
	}
	
	//查看日志
	public function orderLog($sn=''){
		if($sn=='') return $this->status(false);
		$rs=$this->get_all('*',array('order_sn'=>$sn),'order_log');
		return $this->status(true,$rs);
	}
	//导出
	public function exportOrder($tj=array(),$tj2=array()){
		$title='订单报表';
		$fields=array(
				'order_sn'     =>'订单号',
				'user_name'    =>'会员名称',
				'total_price'  =>'总价',
				'cost_price'   =>'成本价',
				'profit'       =>'利润',
				'amount'       =>'数量',
				'order_status' =>'订单状态',
				'payee'        =>'收货人',
				'phone'        =>'电话',
				'add_time'     =>'下单时间',
		);
		if($exportIds=='all'){
			$this->exportCSV($title,$fields,'order',array(),array('join'=>'customer','on'=>'b.uid=a.id'));
		}else{
			$rs = $this->get_all('*',$tj,'order',$tj2);
			foreach($rs as $v){
				$data[]=array(
					'order_sn'    =>$v['order_sn'],
					'user_name'   =>$v['user_name'],
					'user_id'     =>$v['user_id'],
					'total_price' =>$v['total_price'],
					'cost_price'  =>$v['cost_price'],
					'profit'      =>$v['total_price']-$v['cost_price'],
					'amount'      =>$v['amount'],
					'order_status'=>$v['order_status'],
					'payee'       =>$v['payee'],
					'phone'       =>$v['phone'],
					'add_time'    =>date('Y-m-d H:i:s',$v['add_time']),
				);
			}
			$arr=array();
			foreach($tj as $k=>$v) $arr[$k]="value:".$v;
			$count=array_pop($this->countPrice($arr,array(),
			'sum(total_price) as total_price,sum(cost_price) as cost_price,sum(amount) as amount'));
			$data[]=array(
				'order_sn'=>"",'user_name'=>'统计',
				'total_price'=>sprintf("%.2f",$count['total_price']),
				'cost_price'=>sprintf("%.2f",$count['cost_price']),
				'profit'    =>sprintf("%.2f",$count['total_price']-$count['cost_price']),
				'amount'    =>$count['amount'],
				'order_status'=>'','payee'=>'','phone'=>'','add_time'=>'');
			$this->export($title,array(array('name'=>$title,'data'=>$data,'fields'=>$fields)));
		}
	}
	
	// 验证订单是否属于用户的
	function checkOrderIsUser($sn,$user_id){
		return  $this->get_one('id',array('order_sn' => $sn,'user_id' => $user_id),$this -> table);
	}
	
	// 获取店铺发货标志
	public function getShipStatus($shop_id,$id){
		if(empty($id) || !is_numeric($id) || empty($shop_id) || !is_numeric($shop_id)){
			return false;
		}
		$ship_info = $this->get_one('ship_status',array('id' => $id,'shop_id' => $shop_id),$this -> table);
		if(!$ship_info){
			return false;
		}else{
			return $ship_info['ship_status'];
		}
	}
	
	// 获取订单发货标志
	public function getOrderStatus($shop_id,$id){
		if(empty($id) || !is_numeric($id) || empty($shop_id) || !is_numeric($shop_id)){
			return false;
		}
		$order_info = $this->get_one('order_status',array('id' => $id,'shop_id' => $shop_id),$this -> table);
		if(!$order_info){
			return false;
		}else{
			return $order_info['order_status'];
		}
	}
	
	// 修改订单为完成状态
	public function updateShipStatusInConfirm($user_id,$order_sn){
		if(empty($user_id) || !is_numeric($user_id) || empty($order_sn)){
			return false;
		}
		return $this -> db -> update($this -> table,array('ship_status'=>3),array('order_sn'=>$order_sn,'user_id'=>$user_id));
	}

	// 获取发货状态
	public function getShipStatusByUserId($user_id,$order_sn){
		if(empty($user_id) || !is_numeric($user_id) || empty($order_sn)){
			return false;
		}
		$ship_info = $this->get_one('ship_status',array('order_sn' => $order_sn,'user_id' => $user_id),$this -> table);
		if(!$ship_info){
			return false;
		}else{
			return $ship_info['ship_status'];
		}
	}
	
	// 验证订单是否属于店铺的
	public function checkOrderIsShop($sn,$shop_id){
		if(empty($sn) || !is_numeric($sn) || empty($shop_id) || !is_numeric($shop_id)){
			return false;
		}
		return  $this->get_one('id',array('order_sn' => $sn,'shop_id' => $shop_id),$this -> table);
	}
	
	// 修改未发货订单价格
	public function changePrice($sn,$price){
		if(empty($sn) || !is_numeric($sn) || empty($price) || !is_numeric($price)){
			return false;
		}
		return $this -> db -> update($this -> table,array('total_price'=>$price),array('order_sn'=>$sn,'order_status'=>1));
	}

	// 记录修改价格记录
	function logChangePrice($row){
		if( empty($row) || !is_array($row) || empty($row['original_price']) || !is_numeric($row['original_price']) || empty($row['change_price']) || !is_numeric($row['change_price']) || empty($row['order_sn']) || !is_numeric($row['order_sn'])){
			return false;
		}
		$row['type'] 		=4;
		$row['staff'] 		=2;
		$row['add_time'] 	=time();
		return $this->db->insert('order_log',$row);
	}
	
	// 根据订单编号获取信息
	function getById($sn){
		if(empty($sn) || !is_numeric($sn)){
			return false;
		}
		return $this->get_one('*',array('order_sn'=>$sn),$this -> table);
	}
	
	// 根据订单号获取修改价格记录
	function getOrderLogByChangeInfo($sn){
		if(empty($sn) || !is_numeric($sn)){
			return false;
		}
		return $this->get_all('*',array('order_sn'=>$sn,'type'=> 4),'order_log',array('orderby' => array('add_time' => 'desc')));
	}
	
	// 获取最近成交订单信息
	function getRecentList($limit=6){
		return $this->get_all('*',
			array('a.type'=>1),
			$this ->table,
			array(
				'join'=>'user',
				'on'=>'b.shop_id=a.id'
				,'a_fields'=>'a.vender,a.username',
				'order'=>'id desc',
				'limit'=>$limit,
				'b_fields'=> 'b.id')
			);
	}
	
	// 获取商品的数量
	public function getAmount($order_id){
		if(empty($order_id) || !is_numeric($order_id)){
			return false;
		}
		$data['zhenpi'] = 0;
		$data['fangpi'] = 0;
		$order_detail = $this->get_all('*',array('order_id'=>$order_id),'order_detail');
		
		if(!$order_detail) { return false; }
		foreach($order_detail as $key => $order){
			$order_info = $this->get_all('*',array('b.o_id'=>$order['id']),'order_info',array('join'=>'goods','on'=>'b.goods_id=a.id','a_fields'=>'a.pi_type','limit'=>$limit,'b_fields'=> 'b.goods_id,goods_amount,goods_title,rzg_amount'));
			#echo '<pre>';print_R($order_info);exit;
			if($order_info){
				foreach($order_info as $key => $v){
					if($v['pi_type'] ==1){
						if($v['goods_amount']){
							$data['zhenpi']+=$v['goods_amount'];
						}
					}else if($v['pi_type'] ==2){
						if($v['rzg_amount']){
							$data['fangpi']+=$v['rzg_amount'];
						}
						
					}
				}
			}
		}
		return '真皮:'.$data['zhenpi'].'英尺'.' 仿皮:'.$data['fangpi'].'寸';
	}
	
}

?>